import { createRouter, createWebHashHistory } from 'vue-router'
import login from "@/views/login";
import home from "@/views/index";
import sys from "@/router/sys/index";


const routes = [
    {
        path : "/login",
        name: '/login',
        component : login,
    },
    {
        path : "/",
        name: '/',
        component : home,
        children:[
            ...sys,
        ],
    },
    // ...back,
]


const router = createRouter({
    history: createWebHashHistory(),
    routes:  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
    // ...
    if (to.matched.length ===0) {  //如果未匹配到路由
        // from.path? next({ path:from.path}) : next('/');   //如果上级也未匹配到路由则跳转主页面，如果上级能匹配到则转上级路由
        next('/404')
    } else {
        next();    //如果匹配到正确跳转
    }
})

// 检查路由是否已存在
const routeExists = (path) => {
    return router.getRoutes().some(route => route.path === path);
};

// 动态添加路由
export const addDynamicRoutes = (menuList) => {
    const generateRoutes = (menuList) => {
        menuList.forEach(menu => {
            if (menu.type === 1 && !routeExists(menu.path)) { // **检查路由是否存在**
                let path = menu.path;
                if (path.startsWith('/')) {
                    path = path.slice(1);
                }
                const route = {
                    path: '/' + path,
                    name: path,
                    meta: {
                        title: menu.name,
                        keepAlive: true,
                    },
                    components: {
                        //index为声明的router-view的name
                        index: () =>
                            import(`@/views/${path}`)
                    }
                };
                router.addRoute('/', route); // **动态添加到 home.children**
            }

            if (menu.children && menu.children.length > 0) {
                generateRoutes(menu.children);
            }
        });
    };

    generateRoutes(menuList);
};
export default router